const useWinScroll = defineStore("winScroll", () => {
  const translateY = ref(0);
  const speed = 6;
  function handleWinScroll() {
    translateY.value = Math.min(translateY.value + speed, 48);
    const timer = window.setTimeout(() => {
      clearTimeout(timer);
      if (!isVisible.value) {
        translateY.value = 0;
      }
    }, 1000);
  }

  const targetEl = useTemplateRef<HTMLDivElement>("targetRef");
  const isVisible = ref(false);
  const handleIntersection = (entries: IntersectionObserverEntry[]) => {
    const entry = entries[0];
    isVisible.value = entry.isIntersecting;
  };
  let observer: IntersectionObserver | null = null;
  function setupObserver() {
    if (targetEl.value) {
      observer = new IntersectionObserver(handleIntersection, {
        root: null,
        threshold: 0,
      });
      observer.observe(targetEl.value);
    }
  }

  onMounted(() => {
    window.addEventListener("scroll", handleWinScroll, {
      passive: true,
    });
  });

  onUnmounted(() => {
    window.removeEventListener("scroll", handleWinScroll);
    if (observer) {
      observer.disconnect();
    }
  });
  return {
    translateY,
    isVisible,
    setupObserver,
  };
});
export const useWinScrollRefs = () => {
  return storeToRefs(useWinScroll());
};
export default useWinScroll;
